package com.k2data.k2app.util.schedule;

import com.k2data.k2app.mapper.TaskQuartzMapper;
import com.k2data.k2app.service.TaskService;
import org.apache.log4j.Logger;
import org.quartz.*;
import org.springframework.stereotype.Component;

/**
 *
 * @Description: 若一个方法一次执行不完下次轮转时则等待改方法执行完后才执行下一次操作
 */
@Component
@DisallowConcurrentExecution
public class QuartzJobFactory implements Job {
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException{
		Logger logger = Logger.getLogger(QuartzJobFactory.class);
		logger.debug("任务成功运行");
		ScheduleJob scheduleJob = (ScheduleJob)context.getMergedJobDataMap().get("scheduleJob");
		logger.debug("任务名称 = [" + scheduleJob.getJobName() + "]");
		TaskService taskService = MyApplicationContextUtil.getBean("taskService");
		try {
			taskService.run(Long.parseLong(scheduleJob.getJobName()),"auto");
		} catch (Exception e) {
			System.out.println("定时任务运行出错"+e.getMessage());
			if(!e.getMessage().contains("正在运行")){
				ScheduleJobService scheduleJobService = MyApplicationContextUtil.getBean("scheduleJobService");
				try {
					logger.debug("删除定时任务");
					scheduleJobService.removeJob(scheduleJob);
					logger.debug("删除任务记录");
					TaskQuartzMapper taskQuartzMapper= MyApplicationContextUtil.getBean("taskQuartzMapper");
					taskQuartzMapper.delete(scheduleJob);
				} catch (SchedulerException e1) {
					e.printStackTrace();
					logger.debug("删除定时任务出错！"+e.getMessage());
				}
			}else{
				System.out.println("定时任务正在运行，本次任务推到下次执行");
			}
		}
	}
}
